"use client";

import React, { useMemo } from "react";

import { useState } from "react";
import { Card, Button, Input, List, Space, message } from "antd";
import { LikeOutlined } from "@ant-design/icons";
import moment from "moment";
import { commentControllerCreate } from "@/app/servers/api/comment";
import {
  articleLikeControllerCreate,
  articleLikeControllerRemove,
} from "@/app/servers/api/articleLike";

export interface DetailProps {
  article: API.ArticleDetailDto;
}
const Detail: React.FC<DetailProps> = ({ article }) => {
  const [comments, setComments] = useState<API.Comment[]>(article.comments);
  const [newComment, setNewComment] = useState("");
  const [liked, setLiked] = useState(article.isLike);

  const handleLike = async () => {
    if (liked) {
      await articleLikeControllerRemove({
        id: article.id.toString(),
      });
      article.likes--;
    } else {
      await articleLikeControllerCreate({
        articleId: article.id,
      });
      article.likes++;
    }
    setLiked(!liked);
    message.success(liked ? "已取消点赞" : "点赞成功");
  };

  const handleComment = async () => {
    if (!newComment.trim()) {
      message.error("评论内容不能为空");
      return;
    }
    const { data } = await commentControllerCreate({
      articleId: article.id,
      content: newComment,
    });
    setComments([...comments, data]);
    setNewComment("");
    message.success("评论成功");
  };

  const ArticleContent = useMemo(() => {
    return (
      <HtmlContent
        key={article.content}
        htmlString={article.content}
      ></HtmlContent>
    );
  }, [article.content]);

  return (
    <div className="container mx-auto px-4 py-8 max-w-4xl">
      {article ? (
        <>
          <Card title={article.title}>
            <div className="mb-4 text-gray-600">
              作者: {article.user.username} | 发布时间:{" "}
              {moment(article.createdAt).format("YYYY-MM-DD HH:mm:ss")} 观看次数
              {article.views}
            </div>
            {ArticleContent}
            <div>
              <Space className="mt-4 mb-4">
                {/* 观看次数 */}
                <Button
                  icon={<LikeOutlined />}
                  onClick={handleLike}
                  type={liked ? "primary" : "default"}
                >
                  点赞 ({article.likes})
                </Button>
              </Space>
            </div>
          </Card>

          <div className="mt-8">
            <h3 className="text-xl font-bold mb-4">评论</h3>
            <div className="flex gap-2 mb-4">
              <Input.TextArea
                value={newComment}
                onChange={(e) => setNewComment(e.target.value)}
                placeholder="写下你的评论..."
                rows={2}
              />
              <Button type="primary" onClick={handleComment}>
                发表评论
              </Button>
            </div>

            <List
              itemLayout="horizontal"
              dataSource={comments}
              renderItem={(comment) => (
                <List.Item>
                  <List.Item.Meta
                    title={comment.user.username}
                    description={moment(comment.updatedAt).format(
                      "YYYY-MM-DD HH:mm:ss"
                    )}
                  />
                  <div>{comment.content}</div>
                </List.Item>
              )}
            />
          </div>
        </>
      ) : (
        <div>加载中...</div>
      )}
    </div>
  );
};
export default Detail;

const HtmlContent = ({ htmlString }: { htmlString: string }) => {
  return <div dangerouslySetInnerHTML={{ __html: htmlString }} />;
};
